const fs = require("fs");
const path = require("path");

const directory = {  
  name: 'root',  
  metadata: {  
    createdAt: new Date(),  
    modifiedAt: new Date()  
  },  
  children: [  
    {  
      name: 'folder1',  
      metadata: {  
        createdAt: new Date(),  
        modifiedAt: new Date()  
      },  
      children: [  
        {  
          name: 'file1.txt',  
          metadata: {  
            createdAt: new Date(),  
            modifiedAt: new Date(),  
            contentSize: 1024  
          },  
          children: []  
        },  
        {  
          name: 'file2.jpg',  
          metadata: {  
            createdAt: new Date(),  
            modifiedAt: new Date(),  
            contentSize: 5120  
          },  
          children: []  
        }  
      ]  
    },  
    {  
      name: 'folder2',  
      metadata: {  
        createdAt: new Date(),  
        modifiedAt: new Date()  
      },  
      children: []  
    }  
  ]  
};

function getImagesInFolder(folderPath) {
  const images = []; // 存放图片路径的数组
  const catalogue = [];

  function traverseDirectory(dirPath) {
    const files = fs.readdirSync(dirPath);

    for (let file of files) {
      const fullFilePath = path.join(dirPath, file);

      if (fs.statSync(fullFilePath).isDirectory()) {
        traverseDirectory(fullFilePath); // 如果是子目录则递归调用自身处理该子目录
      } else {
        const extname = path.extname(file);
        const imgFormat = [".jpg", ".jpeg", ".png", "BMP", "svg"];

        if (imgFormat.includes(extname)) {
          images.push(fullFilePath); // 将符合条件的图片路径添加到images数组中
        }
      }
    }
  }

  traverseDirectory(folderPath);

  return images;
}

try {
  // 文件夹路径
  /** 常用文件夹路径
   * wallPaper壁纸路径 "F:/Program Files/Steam/steamapps/workshop/content"
   *  */
  const folderPath = fs.readFileSync("文件夹路径.txt");
  const images = getImagesInFolder(folderPath?.toString());

  // 将数组转换为JSON字符串
  const jsonString = JSON.stringify(images);
  // 同步写入JSON文件
  fs.writeFileSync("images.json", jsonString);
  console.log("Array has been saved to myArray.json");
} catch (err) {
  console.error("An error occurred:", err);
}
